import {
  Button,
  Checkbox,
  Icon,
  ImgDefault,
  imgPreview,
  Input,
  message,
  Modal,
  Space,
  Spin
} from "@bytedance/mona-ui"
import React, {
  forwardRef,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from "react"

import { generatedAiInit } from "./generatedAiImages"

import "./index.scss"

function AiImage(props: any, ref: any) {
  const { setAddInfoData, product_id, img_format } = props
  if (!setAddInfoData || !setAddInfoData.length) return null
  let [aipProtlist, setAipProtlist] = useState<any>([])

  // console.log('setAddInfoData', setAddInfoData)
  useMemo(() => {
    aipProtlist = JSON.parse(JSON.stringify(setAddInfoData)).map(
      (item: any, index: number) => {
        // const copyLitser = item
        const aldList = JSON.parse(JSON.stringify(item))
        const fortItem = {
          lodinAiStatus: false,
          aldList,
          inputtags: [],
          sehtinputtxt: "",
          maidianList: [
            {
              url: "https://lf3-cm.ecombdstatic.com/obj/tosdr-ecom-material/recommend_style.jpg",
              title: "推荐风格",
              select: true,
              extra_map: {
                one_one_ratio_template_ids:
                  "7359178451200295178,7359178451200278794,7359178451183583539,7359178658122236187,7359178658122219803,7359178658122203419,7359178451200360714,7359178658122301723,7359178658122285339,7359178658122268955,7359178658122252571",
                three_four_ratio_template_ids:
                  "7359897417560359194,7359578334218486043,7359578334218469659,7359179295224283430,7359179295224267046,7359179295224250662,7359178746500317450,7359897417560424730,7359897417560408346,7359897417560391962,7359897417560375578"
              },
              scene_type: "RECOMMEND"
            },
            {
              url: "https://lf3-cm.ecombdstatic.com/obj/tosdr-ecom-material/jia_bao_kuang.jpg",
              title: "加包框",
              select: false,
              extra_map: {
                one_one_ratio_template_ids:
                  "7359178451200295178,7359178451200278794,7359178451200262410,7359178451200246026,7359178451183583539,7359178451183567155,7359178451183550771,7359178451183534387,7359178451183518003,7359178451183501619,7359178451183485235,7359178451183468851",
                three_four_ratio_template_ids:
                  "7359897417560359194,7359578334218486043,7359578334218469659,7359578334218453275,7359578334218436891,7359578334218420507,7359577873130307850,7359577873130291466,7359577873130275082,7359577873130258698,7359577873130242314,7359577873130225930,7359190270778294578,7359190270778278194,7359179805343990025,7359179805343973641,7359179805343957257,7359179805343940873,7359179805343924489,7359179805343908105,7359179805343891721,7359179805343875337,7359179295224348966,7359179295224299814"
              },
              scene_type: "TEMPLATE"
            },
            {
              url: "https://lf3-cm.ecombdstatic.com/obj/tosdr-ecom-material/jia_tie_zi.jpg",
              title: "加贴纸",
              select: false,
              extra_map: {
                one_one_ratio_template_ids:
                  "7359178658122236187,7359178658122219803,7359178658122203419,7359178451200360714,7359178451200344330,7359178451200327946,7359178451200311562",
                three_four_ratio_template_ids:
                  "7359179295224283430,7359179295224267046,7359179295224250662,7359178746500317450,7359178746500301066,7359178746500251914,7359178746500235530"
              },

              scene_type: "STICKER"
            },
            {
              url: "https://lf3-cm.ecombdstatic.com/obj/tosdr-ecom-material/jian_yue.jpg",
              title: "简约",
              select: false,
              extra_map: {
                one_one_ratio_template_ids:
                  "7359178658122301723,7359178658122285339,7359178658122268955,7359178658122252571",
                three_four_ratio_template_ids:
                  "7359897417560424730,7359897417560408346,7359897417560391962,7359897417560375578"
              },
              scene_type: "SELLPOINT"
            }
          ],
          list: item.map((item2: any, iter: number) => {
            item2.selectStatus = false
            if (!iter) item2.selectStatus = true

            item2.run_end_images = []
            item2.imsdata = []
            item2.old_url = item2.url

            item2.runFunc = item2.url
              ? generatedAiInit({
                  img_format,
                  product_id: product_id,
                  url: item2.url,
                  cb: function (data) {
                    this.run_end_images.push(...data.run_end_image_obj)

                    this.run_end_images = item2.runFunc?.myseta(
                      this.run_end_images
                    )
                    this.imsdata = this.run_end_images
                    setAipProtlist([...aipProtlist])
                  }.bind(item2),
                  setGetAiImageLodinStatus: (status: any) => {
                    // console.log('设置加载中的动画效果', status, item, fortItem)
                    fortItem.lodinAiStatus = status
                    setAipProtlist([...aipProtlist])
                  },
                  stopRun: true
                })
              : null
            return item2
          })
        }
        return fortItem
      }
    )
    // console.log('aipProtlist', aipProtlist)
    setAipProtlist(aipProtlist)
  }, [setAddInfoData])

  const aiImageRefs = useRef<any>([])
  useImperativeHandle(ref, () => ({
    someMethod
  }))
  function someMethod() {
    let oldList = ""
    let newUrl = ""

    aipProtlist.forEach((item) => {
      item.aldList.forEach((item2: any) => {
        oldList = oldList + item2.url
      })
      item.list.forEach((item2: any) => {
        newUrl = newUrl + item2.url
        item2.res_url = item2.url
      })
    })
    if (newUrl === oldList) {
      message.error("没有新的图片")
      return false
    }
    return aipProtlist.map((item) => {
      return item.list
    })
  }
  let apiter = img_format == 1 ? 1 : 1.33333
  const inputRef = useRef<any>([])

  return (
    <div className="aiBoxContent">
      <div className="leftList">
        <Space direction="vertical" size={10} align="center">
          {aipProtlist.map((item, index) => {
            if (!item.list[0].url) return null
            return (
              <Spin spinning={item.lodinAiStatus}>
                <div className="setConters">
                  <ImgDefault
                    imgSrc={item.list[0].url}
                    key={index}
                    className="imgDefault"
                    width={36}
                    height={36 * apiter}></ImgDefault>
                  <Button
                    size="small"
                    onClick={() => {
                      aiImageRefs.current[index]?.scrollIntoView({
                        behavior: "smooth"
                      })
                      item.list[0].runFunc?.run()
                    }}>
                    生成第{index + 1}组
                  </Button>
                </div>
              </Spin>
            )
          })}
        </Space>
        <div className="inBottome">
          <Button
            size="small"
            type="primary"
            onClick={() => {
              aipProtlist.forEach((item, index) => {
                item.list[0].runFunc?.run()
              })
            }}>
            生成全部
          </Button>
        </div>
      </div>
      <div className="rightConte">
        <Space
          direction="vertical"
          size={30}
          style={{
            width: "100%"
          }}>
          {aipProtlist.map((item, index) => {
            if (!item.list[0].url) return null
            return (
              <Spin spinning={item.lodinAiStatus}>
                <div className="cinern" key={index}>
                  <div
                    className="butyers"
                    style={{
                      color: "#252931",
                      fontSize: 14,
                      fontStyle: "normal"
                    }}
                    ref={(el) => {
                      if (el) {
                        aiImageRefs.current[index] = el
                      }
                    }}>
                    第{index + 1}组 图片
                  </div>
                  <Space align="center" className="butyers">
                    <Button
                      size="mini"
                      type="secondary"
                      onClick={() => {
                        // console.log('随机选择图片')
                        const selctciter = []
                        item.list.forEach((itemse, inter) => {
                          selctciter.push(...itemse.run_end_images)
                        })
                        if (!selctciter || selctciter.length === 0)
                          return Modal.warning({
                            title: "提示",
                            content: "请先点击生成图片",
                            onOk() {
                              item.list[0].runFunc?.run()
                            }
                          })
                        item.list.forEach((ityer) => {
                          // parseInt  Math.floor(Math.random() * 10);
                          ityer.url =
                            selctciter[
                              Math.floor(Math.random() * selctciter.length)
                            ].img_url || ityer.url
                        })
                        setAipProtlist([...aipProtlist])
                        // console.log('selctciter', selctciter)
                      }}>
                      随机选择
                    </Button>
                    {item.list.find(
                      (itemse, inter) => itemse.url !== item.aldList[inter].url
                    ) && (
                      <Button
                        size="mini"
                        type="primary"
                        onClick={() => {
                          item.list.forEach((itemerr, indexser) => {
                            itemerr.url = item.aldList[indexser].url
                          })
                          setAipProtlist([...aipProtlist])
                        }}>
                        恢复所选
                      </Button>
                    )}
                  </Space>
                  <div className="contentItemInfos">
                    <div className="lefutContentImgae">
                      <Space direction="vertical" align="center">
                        {item.list.map((img, inter) => {
                          return (
                            <Space
                              direction="vertical"
                              align="center"
                              size={0}
                              className="sheclter">
                              <ImgDefault
                                imgSrc={img.url}
                                key={inter}
                                className="imgDefault"
                                width={img.selectStatus ? 85 : 65}
                                height={
                                  img.selectStatus ? 85 * apiter : 65 * apiter
                                }
                                style={
                                  {
                                    // transition: 'all .3s',
                                  }
                                }
                                onClick={() => {
                                  item.list.forEach((item, index) => {
                                    item.selectStatus = false
                                  })
                                  img.selectStatus = true
                                  setAipProtlist([...aipProtlist])
                                }}></ImgDefault>
                              {img.selectStatus && (
                                <Checkbox
                                  className="shuyerbser"
                                  checked={true}
                                  size="small"
                                />
                              )}
                              {item.aldList[inter].url != img.url && (
                                <Button
                                  type="link"
                                  className="getrtighter"
                                  onClick={() => {
                                    // console.log('item', item.aldList[inter].url, img.url)
                                    img.url = item.aldList[inter].url
                                    setAipProtlist([...aipProtlist])
                                  }}>
                                  恢复
                                </Button>
                              )}
                              <Button
                                size="mini"
                                onClick={() => {
                                  img.runFunc?.run()
                                }}>
                                Ai成图
                              </Button>
                            </Space>
                          )
                        })}
                      </Space>
                    </div>
                    <div className="scterImgList">
                      {/* <ItemImage ref={(el) => {
                                    console.log('e00l', el, index)
                                    if (el) {
                                        aiImageRefs.current[index] = el
                                    }}}></ItemImage> */}

                      {/* 生成的结果 */}
                      <Space wrap>
                        {item.list.map((img, inter) => {
                          // console.log('img', item.list)
                          if (img.runFunc?.run_status == 5) {
                            return img.runFunc?.run_err_text
                          }
                          return (
                            !!(
                              img.run_end_images && img.run_end_images.length
                            ) && (
                              <>
                                {img.run_end_images.map((itemImage, index) => {
                                  return (
                                    <div className="showImgcmax">
                                      <ImgDefault
                                        imgSrc={itemImage?.img_url}
                                        key={index}
                                        className="imgDefault"
                                        width={120}
                                        height={120 * apiter}
                                        onClick={() => {
                                          item.list.forEach((item, index) => {
                                            if (item.selectStatus) {
                                              item.url = itemImage.img_url
                                            }
                                          })
                                          setAipProtlist([...aipProtlist])
                                        }}></ImgDefault>
                                      <div className="conterItemStatus">
                                        <div
                                          className="itemcie"
                                          onClick={(e) => {
                                            e.stopPropagation()
                                            console.log(
                                              "imagesUrl",
                                              itemImage?.img_url
                                            )
                                            imgPreview({
                                              defaultIndex: 0,
                                              imgUrl: [itemImage?.img_url]
                                            })
                                          }}>
                                          <Icon
                                            type="SeeIcon"
                                            className="setIcon"
                                            onClick={(e) => {}}></Icon>
                                        </div>
                                      </div>
                                    </div>
                                  )
                                })}
                                <Spin
                                  spinning={img?.runFunc?.run_status == 4}
                                  style={{
                                    width: 120
                                  }}></Spin>
                              </>
                            )
                          )
                        })}
                      </Space>
                    </div>
                  </div>
                  <div className="forRightMaidian">
                    <Space align="start">
                      <Space direction="vertical">
                        <div className="topTitle">卖点图风格</div>
                        <Space align="center">
                          {item.maidianList?.map((itemw3, index) => {
                            return (
                              <Space
                                direction="vertical"
                                className="upcontepouer"
                                size={0}
                                align="center"
                                key={index}>
                                <ImgDefault
                                  imgSrc={itemw3.url}
                                  width={60}
                                  height={60}
                                  onClick={() => {
                                    item.maidianList.forEach((item) => {
                                      item.select = false
                                    })
                                    itemw3.select = true
                                    setAipProtlist([...aipProtlist])
                                    // setMaidianList([...item.maidianList])
                                    // setMaidianList((itemsd) => {
                                    //     itemsd.forEach((item) => {
                                    //         item.select = false
                                    //     })
                                    //     item.select = true
                                    //     return [...itemsd]
                                    // })
                                  }}></ImgDefault>
                                <div className="title">{itemw3.title}</div>
                                {itemw3.select && (
                                  <Checkbox
                                    checked={true}
                                    className="uoyers"></Checkbox>
                                )}
                              </Space>
                            )
                          })}
                        </Space>
                      </Space>
                      <Space direction="vertical">
                        <div className="topTitle">自定义卖点词</div>
                        <div
                          className="inputerContent"
                          onClick={() => {
                            // inputRef.current?.focus()
                            // console.log('inputRef', inputRef)
                            inputRef.current[index]?.focus()
                          }}>
                          <div className="inputwaike">
                            <div className="topcontentli">
                              <Space wrap>
                                {item.inputtags.map((item, index) => {
                                  return (
                                    <Space
                                      className="tagContent"
                                      size={2}
                                      key={index}
                                      align="center">
                                      <div className="textBox">{item}</div>
                                      <div
                                        className="clearIcon"
                                        onClick={() => {
                                          // 删除当前
                                          // inputtags.slice(index, 1)
                                          // setInputtags(inputtags)
                                        }}>
                                        <Icon type="CloseIcon"></Icon>
                                      </div>
                                    </Space>
                                  )
                                })}
                              </Space>
                              <Input
                                size="small"
                                value={item.sehtinputtxt}
                                placeholder={
                                  item.inputtags && item.inputtags.length
                                    ? ""
                                    : "可选输入，多个用逗号/空格隔开"
                                }
                                onBlur={(e) => {
                                  if (e.target.value) {
                                    item.inputtags = [
                                      ...item.inputtags,
                                      e.target.value
                                    ].splice(0, 10)
                                    item.sehtinputtxt = ""
                                    // setInputtags([...inputtags, e.target.value])
                                    // setSehtinputtxt('')
                                    setAipProtlist([...aipProtlist])
                                  }
                                }}
                                onPressEnter={(e) => {
                                  if (e.target.value) {
                                    item.inputtags = [
                                      ...item.inputtags,
                                      e.target.value
                                    ].splice(0, 10)
                                    item.sehtinputtxt = ""
                                    // setInputtags([...inputtags, e.target.value])
                                    // setSehtinputtxt('')
                                    setAipProtlist([...aipProtlist])
                                  }
                                }}
                                onKeyDown={(e) => {
                                  if (
                                    e.key === "Backspace" &&
                                    !inputRef.current[index]?.state.value
                                  ) {
                                    item.inputtags = item.inputtags.slice(
                                      0,
                                      item.inputtags.length - 1
                                    )
                                    // setInputtags(inputtags.slice(0, inputtags.length - 1))
                                    setAipProtlist([...aipProtlist])
                                  }
                                }}
                                bordered={false}
                                style={
                                  {
                                    // width: '22px',
                                    // textOverflow: 'ellipsis'
                                    // width: 'auto'
                                  }
                                }
                                ref={(el) => {
                                  if (el) {
                                    inputRef.current[index] = el
                                  }
                                }}
                                openComposition
                                onChange={(e) => {
                                  console.log("e", e)
                                  // setSehtinputtxt(e.target.value)
                                  item.sehtinputtxt = e.target.value
                                  setAipProtlist([...aipProtlist])
                                  if (
                                    e.target.value.includes(" ") ||
                                    e.target.value.includes(",") ||
                                    e.target.value.includes("，")
                                  ) {
                                    const arr = e.target.value.split(/[\s,，]+/)
                                    console.log("arr", arr)
                                    item.inputtags = [
                                      ...item.inputtags,
                                      ...arr.filter((item) => item !== "")
                                    ].splice(0, 10)
                                    // setInputtags([...inputtags, ...arr.filter((item) => item !== '')])
                                    // setSehtinputtxt('')
                                    item.sehtinputtxt = ""
                                    setAipProtlist([...aipProtlist])
                                  }
                                }}
                              />
                            </div>
                            <div className="bottomContentCliearNum">
                              {item.inputtags.length}/10
                            </div>
                          </div>
                        </div>
                      </Space>
                      <Space
                        className="cone"
                        align="end"
                        direction="vertical"
                        style={{
                          // width: '100%',
                          height: "110px"
                        }}>
                        <Button
                          type="primary"
                          onClick={() => {
                            const getFOnyer = item.list.find(
                              (iyt) => iyt.selectStatus
                            )
                            const getSelectType = item.maidianList.find(
                              (iyt) => iyt.select
                            )
                            getFOnyer.runFunc.runMaidian(
                              getFOnyer.old_url,
                              {
                                customized_sell_point: JSON.stringify(
                                  item.inputtags
                                ),
                                one_one_ratio_template_ids:
                                  getSelectType.extra_map
                                    .one_one_ratio_template_ids,
                                three_four_ratio_template_ids:
                                  getSelectType.extra_map
                                    .three_four_ratio_template_ids,
                                scene_type: getSelectType.scene_type
                              },
                              getSelectType.extra_map
                            )
                            // console.log('item', item.list.find(iyt => iyt.selectStatus).runFunc.runMaidian())
                          }}
                          style={{
                            marginTop: 30
                          }}>
                          生成
                        </Button>
                      </Space>
                    </Space>
                  </div>
                </div>
              </Spin>
            )
          })}
        </Space>
      </div>
    </div>
  )
}

export default forwardRef(AiImage)
